var maplet = null;
var polylines = [];
$(document).ready(function () {
    document.getElementById("form").reset();
    initMap();
    initMessage();
    bindEvent();
});

function bindEvent() {
    $('#select_reqioninfo').combobox({
        url: basePath + '/regionInfoAction!getRegionInfoSelectData.action',
        valueField: 'id',
        textField: 'name',
        editable: false
    });

    $('#clear').click(function () {
        maplet.clearOverlays();
        maplet.setMode("drawarea", onDrawarea)
    });

    $('#save').click(function () {
        if (!checkPolyline(maplet.getPolylines())) {
            return;
        }
        var url = basePath + '/cnbdw/fenceInfoAction!add.action';
        if($.trim($('#id').val()) != ''){
            url = basePath + '/cnbdw/fenceInfoAction!update.action';
        }
        $('#form').form('submit', {
            url: url,
            onSubmit: function () {
                if ($(this).form("validate")) {
                    $.messager.progress({title: '提示', text: '正在保存，请稍候 ....'});
                } else {
                    return false;
                }
            },
            success: function (result) {
                try {
                    var r = $.parseJSON(result);
                    if (r.returnFlag) {
                        document.getElementById("form").reset();
                        location.href = basePath + '/cnbdw/smapInfoAction!showFences.action?id=' + $('#smapId').val();
                    }
                    //显示提示信息
                    $.messager.show({
                        title: '提示',
                        msg: r.returnMsg
                    });
                } catch (e) {

                }
                $.messager.progress('close');
            }
        });
    });
}

function initMap() {
    maplet = new Maplet("mmap");
  
  //  maplet.addControl(new MStandardControl());
  //  maplet.DISABLE_DBCLICK_ZOOM=false;
    maplet.centerAndZoom(new MPoint(0, 0), 0);
  
  
    maplet.markerDragAnimation=false;
    
    maplet.showOverview(false,false);
    maplet.setAutoZoom();
  //  maplet.setIwStdSize(500,300);
    document.getElementById('LayerScale').style.display = 'none';
    document.getElementById('ImgCopyright').style.display = 'none';
    $('span:contains("GS(2011)1617")').parent().hide();
   
    onWindowResize();
  //  window.onresize = function () {
    //    onWindowResize();
  //  };

    var geoText = $('#fence_polylinePts').val();
    if ($.trim(geoText) != '') {
        var points = [];
        var point_txts = geoText.split(";");
        $.each(point_txts, function (index, item) {
            points.push(new MPoint(item));
        });
        var ob = {"points": points};
        onDrawarea(ob);
    } else{
        maplet.setMode("drawarea", onDrawarea)
    }
}

function initMessage() {
    $("#mmap").mousemove(function (a) {
        var b = a.pageX, c = a.pageY;
        $("#message").css({top: c + 15, left: b + 10})
    }).mouseover(function () {
        $("#message").show();
        var polylines = maplet.getPolylines();
        if (null == polylines || 0 == polylines.length) {
            $("#message").html("在地图上点击鼠标左键绘制区域，双击结束");
        } else {
            $("#message").html("如果您想重绘区域，点击清除区域按钮后重新在地图上绘制区域");
        }
    }).mouseout(function () {
        $("#message").hide()
    })
}

function onWindowResize() {
    $('#clear').css("left", $('#mmap').position().left);
    $('#clear').css("top", 40);

    var width = $(window).width();
    var height = $(window).height();

  //  maplet.resize(width - 400, height - 50);
    maplet.resize(600,600);
}

function onDrawarea(ob) {
    var brush = new MBrush("green");
    brush.arrow = false;
    brush.style = 0;
    brush.stroke = 1;
    brush.fill = true;
    brush.bgcolor = "blue";
    brush.color = "red";
    brush.bgtransparency = 35;
    var polyline = new MPolyline(
        ob.points,
        brush
    );

    var pointsHtml = [];
    $.each(ob.points, function (index, point) {
        pointsHtml.push('new MPoint(' + point.lon + ', ' + point.lat + ')');
    })
    maplet.addOverlay(polyline);
    polylines.push(polyline);
}

function checkPolyline(polylines) {
    if (polylines == null || polylines.length != 1 || polylines[0].pts == null || polylines[0].pts.length < 3) {
        $.messager.show({style: {right: '', top: document.body.scrollTop + document.documentElement.scrollTop, bottom: ''}, showType: 'slide',
            title: '错误提示',
            msg: '地图上必须定义一个至少包含三个点的区域（仅一个）！',
            timeout: 5000,
            showType: 'slide'
        });
        return false;
    }

    var pts = [];
    $.each(polylines[0].pts, function (index, item) {
        pts.push(item.pid);
    })

    $('#fence_polylinePts').val(pts.join(";"));
    return true;
}